package com.rent.house.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rent.common.entity.ResponseResult;
import com.rent.common.exception.BusinessException;
import com.rent.common.util.JwtUtil;
import com.rent.house.pojo.dto.HousePublishDTO;
import com.rent.house.pojo.dto.PendingHouseDto;
import com.rent.house.pojo.entity.HouseResource;
import com.rent.house.pojo.vo.HouseResourceVo;
import com.rent.house.service.HouseResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.rent.common.enums.UserRole;
import com.rent.common.interceptor.UserContext;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 房源控制器
 */
@RestController
@RequestMapping("/api/house")
@Api(tags = "房源管理")
public class HouseResourceController {

    @Autowired
    private HouseResourceService houseResourceService;

    @PostMapping("/publish")
    @ApiOperation("发布房源")
    public ResponseResult<Map<String, Object>> publishHouse(@Valid @RequestBody HousePublishDTO housePublishDTO) {
        // 将DTO转换为实体类
        HouseResource houseResource = new HouseResource();
        BeanUtils.copyProperties(housePublishDTO, houseResource);

        // 发布房源
        List<String> picUrls = housePublishDTO.getPicUrls();
        Long houseId = houseResourceService.publishHouse(houseResource, picUrls);

        Map<String, Object> result = new HashMap<>();
        result.put("id", houseId);
        result.put("status", 0);
        result.put("auditStatus", 0);

        return ResponseResult.success("房源发布成功，等待审核", result);
    }

    @GetMapping("/list")
    @ApiOperation("房源列表查询")
    public ResponseResult<Page<HouseResourceVo>> listHouses(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNo,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("城市") @RequestParam(required = false) String city,
            @ApiParam("最低价格") @RequestParam(required = false) BigDecimal minPrice,
            @ApiParam("最高价格") @RequestParam(required = false) BigDecimal maxPrice,
            @ApiParam("户型") @RequestParam(required = false) String roomType,
            @ApiParam("关键词") @RequestParam(required = false) String keyword) {

        Page<HouseResourceVo> page = houseResourceService.listHousesWithPics(
                pageNo, pageSize, city, minPrice, maxPrice, roomType, keyword);
        return ResponseResult.success(page);
    }

    @GetMapping("/{id}")
    @ApiOperation("房源详情查询")
    public ResponseResult<HouseResourceVo> getHouseDetail(@ApiParam("房源ID") @PathVariable Long id) {
        HouseResourceVo houseResource = houseResourceService.getHouseDetailWithPics(id);
        if (houseResource == null) {
            throw new BusinessException("房源不存在");
        }
        return ResponseResult.success(houseResource);
    }

    @GetMapping("/search")
    @ApiOperation("搜索房源")
    public ResponseResult<Page<HouseResourceVo>> searchHouses(
            @ApiParam("关键词") @RequestParam String keyword,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNo,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {

        Page<HouseResourceVo> page = houseResourceService.searchHousesWithPics(
                keyword, pageNo, pageSize);
        return ResponseResult.success(page);
    }

    @PutMapping("/update")
    @ApiOperation("更新房源")
    public ResponseResult<?> updateHouse(@Valid @RequestBody HouseResource houseResource) {
        boolean success = houseResourceService.updateHouse(houseResource);
        if (success) {
            return ResponseResult.success("房源更新成功");
        } else {
            return ResponseResult.fail("房源更新失败");
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除房源")
    public ResponseResult<?> deleteHouse(@ApiParam("房源ID") @PathVariable Long id) {
        boolean success = houseResourceService.deleteHouse(id);
        if (success) {
            return ResponseResult.success("房源删除成功");
        } else {
            return ResponseResult.fail("房源删除失败");
        }
    }

    @PutMapping("/audit")
    @ApiOperation("审核房源")
    public ResponseResult<?> auditHouse(
            @ApiParam("房源ID") @RequestParam Long id,
            @ApiParam("审核状态：1-通过，2-拒绝") @RequestParam Integer auditStatus,
            @ApiParam("审核备注") @RequestParam(required = false) String auditRemark) {
        boolean success = houseResourceService.auditHouse(id, auditStatus, auditRemark);
        if (success) {
            return ResponseResult.success("房源审核成功");
        } else {
            return ResponseResult.fail("房源审核失败");
        }
    }

    @GetMapping("/pending")
    @ApiOperation("获取特殊房源列表（管理员：待审核房源，房东：我发布的房源）")
    public ResponseResult<Page<HouseResourceVo>> getPendingHouses(PendingHouseDto pendingHouseDto) {

        Page<HouseResourceVo> pendingHouses = houseResourceService.getPendingHouses(pendingHouseDto);

        return ResponseResult.success(pendingHouses);
    }
}
